from django.shortcuts import render, redirect

from manage_worker import models
from manage_worker.utills.pagination import Pagination


def depart_list(request):
    '''部门列表'''

    queryset = models.Department.objects.all()
    page_object = Pagination(request, queryset=queryset, page_size=2)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }

    return render(request, 'depart_list.html', context)


def depart_add(request):
    if request.method == 'GET':
        return render(request, 'depart_add.html')

    title = request.POST.get('title')
    models.Department.objects.create(title=title)

    return redirect('/depart/list')


def depart_delete(request):
    '''
    删除部门
    :param request:
    :return:
    '''

    id = request.GET.get('id')
    models.Department.objects.filter(id=id).delete()
    return redirect('/depart/list')


def depart_edit(request, id):
    '''
    编辑部门
    :param request:
    :return:
    '''
    if request.method == 'GET':
        obj = models.Department.objects.filter(id=id).first()
        return render(request, 'depart_edit.html', {'obj': obj})
    title = request.POST.get('title')
    models.Department.objects.filter(id=id).update(title=title)
    return redirect('/depart/list')
